# planting_records/forms.py
from django import forms
from .models import PlantingRecord
from field_management.models import Field
from django.utils.translation import gettext_lazy as _

class PlantingRecordForm(forms.ModelForm):
    # Override the field queryset in the __init__ method within the view is often cleaner,
    # but doing it here is also possible if the form is always instantiated with a user.
    def __init__(self, *args, **kwargs):
        # Expect 'user' to be passed in kwargs from the view
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        if user:
            self.fields['field'].queryset = Field.objects.filter(owner=user)

        # Use HTML5 date input for better mobile UX
        self.fields['planting_date'].widget = forms.DateInput(attrs={'type': 'date', 'class': 'form-control'})
        self.fields['expected_harvest_date'].widget = forms.DateInput(attrs={'type': 'date', 'class': 'form-control'})

    class Meta:
        model = PlantingRecord
        # Exclude owner, created_at, updated_at
        fields = ['field', 'rice_variety', 'planting_date', 'seedling_source',
                  'planting_method', 'expected_harvest_date', 'notes']
        widgets = {
            'notes': forms.Textarea(attrs={'rows': 3}),
            # Add 'class': 'form-control' or 'form-select' to other widgets if not using crispy-forms
            'field': forms.Select(attrs={'class': 'form-select'}),
            'planting_method': forms.Select(attrs={'class': 'form-select'}),
        }
        labels = {
            'field': _('选择田块'),
            'rice_variety': _('水稻品种'),
            'planting_date': _('种植日期'),
            'seedling_source': _('秧苗/种子来源'),
            'planting_method': _('种植方式'),
            'expected_harvest_date': _('预计收获日期'),
            'notes': _('备注'),
        }